package com.ydsungan.worldbook.controller;


import com.wordnik.swagger.annotations.ApiOperation;
import com.ydsungan.worldbook.pojo.User;
import com.ydsungan.worldbook.service.UserService;
import com.ydsungan.worldbook.utils.JSONResult;
import com.ydsungan.worldbook.utils.JSONUtils;
import com.ydsungan.worldbook.utils.MD5Utils;
import com.ydsungan.worldbook.utils.UrlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping(path = "/user")
@CrossOrigin   //解决跨域
public class UserController {

    @Autowired
    private UserService userService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @ApiOperation(value="用户登录，未注册用户将自动注册")
    @RequestMapping(value = "/signin", method = RequestMethod.GET)
    @CrossOrigin  //解决跨域
    public JSONResult login(String username, String password, HttpServletRequest request){

        User user = new User();
        user.setUsername(username);
        user.setPassword(MD5Utils.MD5Encode(password,"utf8"));


        Map map = new HashMap();
        map.put("username", username);
        List<User> userList = userService.getUserByMap(map);
        if(userList.size() == 0){
            //自动注册
            user.setScore(0);
            if(userService.register(user)){
                logger.info(username + "---" + password + "注册成功!");
                //利用id和时间戳加密生成token
                String token = MD5Utils.MD5Encode(user.getId() + "" + new Date().getTime(),"utf8");
                //token存进session，并返回给客户端
                request.getSession().setAttribute(user.getId() + "", token);
                map.put("id",user.getId());
                map.put("score",user.getScore());
                map.put("token",token);

                return JSONResult.ok(map);
            }else{
                return JSONResult.errorMsg("注册失败");
            }
        }else{
            //该用户已经存在，自动登录, 检验密码，返回与该用户相关数据
            if(user.getPassword().equals(userList.get(0).getPassword())){
                //登录成功,返回用户
                //利用id和时间戳加密生成token
                String token = MD5Utils.MD5Encode(user.getId() + "" + new Date().getTime(),"utf8");
                //token存进session，并返回给客户端
                request.getSession().setAttribute(user.getId() + "", token);
                User logonUser = userList.get(0);
                map.put("id",logonUser.getId());
                map.put("score",logonUser.getScore());
                map.put("token",token);
                return JSONResult.ok(map);
            }else{
                //账号密码不匹配
                return JSONResult.errorMsg("账号和密码不匹配");
            }
        }

    }

    @ApiOperation(value="修改用户名密码")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    @CrossOrigin  //解决跨域
    public JSONResult updateUser(
            @RequestParam(value = "id") String id,
            @RequestParam(value = "username", required = false, defaultValue = "") String username,
            @RequestParam(value = "password", required = false, defaultValue = "") String password
            ){


        Map map = new HashMap();
        map.put("id", Integer.parseInt(id));
        List<User> userList = userService.getUserByMap(map);

        User user = userList.get(0);

        if(!"".equals(username)){
            user.setUsername(username);
        }

        if (!"".equals(password)){
            user.setPassword(MD5Utils.MD5Encode(password,"utf8"));
        }


        if (userService.updateUser(user)){
            return JSONResult.ok(user);
        }else{
            return JSONResult.errorMsg("更新失败");
        }
    }


}
